<script lang="ts" setup>


import { useVbenModal } from '@vben/common-ui'
import {reactive, ref} from "vue";
import {
  Descriptions,
  DatePicker,
  Tag,
  Select,
  message,
  Input,
  Button,
  Cascader,
  Row,
  Col,
  Modal as AntModal,
  Spin,
} from "ant-design-vue";
import {useDebounceFn} from "@vueuse/core";

import {
  approval,
  createGoodsPurchase,
  editGoodsPurchase,
  getFactoryAll,
  getGoodsPurchase,
  getTreeAll,
  getWareHouse, markDetailComplete
} from "#/api/goodsPurchase";
import {DictAddInit, getFactoryIndex} from "#/api/goods";
import goodsList from "../../modules/goodsList.vue";
import updateLog from "./updateLog.vue"
import StockDetail from "./StockDetail.vue"
import againstDialog from "./againstDialog.vue"

import type {VxeTableGridOptions} from "@vben/plugins/vxe-table";
import {useVbenVxeGrid} from "#/adapter/vxe-table";
const inputDisabled = ref(true)
let goods_purchase_id = ref(0)
const edit= ref()
type EmitEvents = {
  close: {};
};
const emit = defineEmits<EmitEvents>();
const typeOptinos = [
  {
    value: 8,
    label: '成品#首单',
  },
  {
    value: 9,
    label: '加工#补单',
  },
  {
    value: 10,
    label: '加工#首单',
  },
  {
    value: 11,
    label: '成品#补单',
  },
  {
    value: 12,
    label: '成品#加单',
  },
  {
    value: 13,
    label: '加工#加单',
  },
  {
    value: 99,
    label: '待买手拆分',
  },
]

const info = reactive({
  is_completed:0,
  purchase_date: '',
  goods_purchase_sn: '',
  warehouse_id: '',
  supply_id:'',
  purchase_type: '',
  manual_no: '',
  fk_type:'',
  fk_rule:'',
  remark:'',
  pack_factory:[],
  purchase_type_text:'',
  is_completed_warehouse:0,
  bom_list:[] as any,
  only_warehouse:0,
  posted:0,
  goods_purchase_id:0

})

const baseOption = reactive({
  styleCategory: {},
});
const getRemoteBaseOption = () => {
  getTreeAll().then(response => {
    baseOption.styleCategory = response
  });
}

//获取仓库
const wareHouseOptions  = ref<{ label: string; value: number }[]>([])
const handleLoading = ref(false)
const handleWareHouseSearch = useDebounceFn(async (keyword: string) => {
  handleLoading.value = true
  try {
    const { list } = await getWareHouse({
      quick_search: keyword || '',
      page: 1,
      limit: 999,
      initKey: 'id',
      select: true,
    })
    wareHouseOptions.value = list.map((item: any) => ({
      label: item.WarehouseName,
      value: item.id,
    }))
  } finally {
    handleLoading.value = false
  }
}, 300)

// 第一次打开下拉就触发一次空搜索，把全部选项拿回来
const  handleWarehouse = (open: boolean) => {
  if (open && wareHouseOptions .value.length === 0) {
    handleWareHouseSearch('')
  }
}

// 获取供应商
const factoryOptions  = ref<{ label: string; value: number }[]>([])
const factoryhandleLoading = ref(false)
const handleFactorySearch = useDebounceFn(async (keyword: string) => {
  factoryhandleLoading.value = true
  try {
    const { list } = await getFactoryIndex({
      quick_search: keyword || "",
      page: 1,
      limit: 999,
      select: true,
      supply_type:2
    })
    factoryOptions.value = list.map((item: any) => ({
      label: item.SupplyNa,
      value: item.id,
    }))
  } finally {
    factoryhandleLoading.value = false
  }
}, 300)

// 第一次打开下拉就触发一次空搜索，把全部选项拿回来
const  handleFactory = (open: boolean) => {
  if (open && factoryOptions.value.length === 0) {
    handleFactorySearch('')
  }
}
//获取包装厂
const factoryAllOptions  = ref<{ label: string; value: number }[]>([])
const factoryAllhandleLoading = ref(false)
const handleFactoryAllSearch = useDebounceFn(async (keyword: string) => {
  factoryAllhandleLoading.value = true
  try {
    const { list } = await getFactoryAll({
      quick_search: keyword || "",
      page: 1,
      limit: 999,
      select: true,
      supply_type:2
    })
    factoryAllOptions.value = list.map((item: any) => ({
      label: item.id_na,
      value: item.id,
    }))
  } finally {
    factoryAllhandleLoading.value = false
  }
}, 300)

// 第一次打开下拉就触发一次空搜索，把全部选项拿回来
const  handleFactoryAll = (open: boolean) => {
  if (open && factoryAllOptions.value.length === 0) {
    handleFactoryAllSearch('')
  }
}
const dictArr = ref({
  paymentMethod:[],
  paymentRule:[],
});

const fktypeChange = ()=>{
  if(info.purchase_type==undefined || !info.purchase_type){
    info.fk_type = '';
    message.error('请先选择订单性质')
    return ;
  }
  refreshfkRule();
}
//成品展示的
let cp = ["2-2-2-2-2"]; // 成品结算规则编码

//加工展示的
let jg = ["3-3-3-1"]; // 加工结算规则名称
//结算规则处理
const refreshfkRule = ()=>{
  if(info.purchase_type==undefined || !info.purchase_type){
    info.fk_type = '';
    message.error('请先选择订单性质');
    return;
  }
  dictArr.value.paymentRule.forEach((item:any)=>{console.log(item);
    console.log(info.fk_type);

    if(item.code == info.fk_type){
      if(info.fk_type != undefined && info.fk_type && info.fk_type=='payable'){

        if([9,10,13].indexOf(Number(info.purchase_type)) !== -1 && jg.indexOf(item.value)  !== -1){
          item.disabled = false;
        }else if([8,11,12].indexOf(Number(info.purchase_type)) !== -1 && cp.indexOf(item.value)  !== -1){
          item.disabled = false;
        }else{
          if(info.fk_rule!==undefined && info.fk_rule && info.fk_rule == item.name){
            info.fk_rule = '';
          }
          item.disabled = true;
        }
      }else{
        item.disabled = false;
      }

    }else{
      if(info.fk_rule!==undefined && info.fk_rule && info.fk_rule == item.name){
        info.fk_rule = '';
      }
      item.disabled = true;
    }
  })
}
const purchasetypeChange = ()=>{
  refreshfkRule();
}

//批量新增
const [goodsModal, goodsModalApi] = useVbenModal({
  connectedComponent: goodsList,
})

function  openGoods(){
  goodsModalApi.setData({}).open()
}



const gridOptions: VxeTableGridOptions = {
  columns: [
    { type: 'seq', width: 50, title: '编号' },
     { type: 'radio', // 单选列
        width: 50, // 列宽
        align: 'center', // 居中
        title: '', // 表头文字
        disabled: (row) => row.is_completed !== 0
      },
     { field: 'operation', title: '操作',width: 70, slots: { default: 'operation' } },
    { field: 'goods_name', title: '选择货品',width: 200, },
     { field: 'color', title: '颜色',width: 70, },
     { field: 'category', title: '分类',width: 180, },
     { field: 'time_category_name',width: 130, title: '时间' },
      { field: 'style_category_id',width: 220, title: '等级', slots: { default: 'style_category_id' } },
     { field: 'confirm_num', title: '数量',width: 90, },
    { field: 'stock_data', title: '分仓明细' ,width: 90, slots: { default: 'stock_data' }},
    { field: 'price', title: '采购价' ,width: 90,},

    { title: '状态', field: 'is_completed', width: 80, slots: { default: 'is_completed'},},
    { field: 'dead_line', title: '预计交期',width: 140,slots: { default: 'dead_line' }, },
    { field: 'remark', title: '备注',slots: { default: 'remark' },width: 180, },
    { field: 'other_pay_remark', title: '其他付款方式',slots: { default: 'other_pay_remark' },width: 250, },
    { field: 'component', title: '成 分',slots: { default: 'component' },width: 350, },
    { field: 'completed_time', title: '完成时间', width: 150, },
  ],
  data: [],
  pagerConfig: {
    enabled: false,
  },
  sortConfig: {
    multiple: true,
  },
}
const [Grid, gridApi] = useVbenVxeGrid({ gridOptions })

function handlePushGoods(datas: any){
  const transformedDatas = datas.map((item:any) => ({
    ...item,
    goods_name:item.goods_no + '/' + item.goods_name + '/' + item.template.template_no,
    color: item.color?.name,
    category:item.cate_name,
    time_category_name:item.time_cate_name,
    style_category_id:item.style_id_arr,
    scm_goods_id:item.goods_id,
    supply_id :item.supply_id,
    goods_id: item.kl_id,
    price: item.purchase_price,
    dead_line: '',
    remark: '',
    total_price: 0,
    product_id: Math.random(),
    confirm_num: 0,
    goods_no: item.good_no,
    style_category_name: item.style_cate_name,
    stock_detail: [],
    goods_code:item.template.template_no,
    shipping_remark:item.shipping_remark,
    supply_ids:item.supply_ids,
  }));
  const tableData = gridApi.grid.getData()
  tableData.push(...transformedDatas)
  gridApi.setGridOptions({data:tableData})

}


//查看更新
const [updateLogModal, updateLogModalApi] = useVbenModal({
  connectedComponent:updateLog,
})

function  openUpdateLog(row: any){
 updateLogModalApi.setData({rowData:row.product_id}).open()
}
//调整分仓
const [stockDetailModal, stockDetailModalApi] = useVbenModal({
  connectedComponent:StockDetail,
  destroyOnClose: true,
})

const goods_no = ref('')
function showStockDetail(row: any){

  goods_no.value = row.goods_no
  console.log(row)
  let inputDisabled =''
  if(edit.value === 'edit'  ){
    inputDisabled='edit'
  }
  const deepCopiedRow = JSON.parse(JSON.stringify(row));
  console.log(deepCopiedRow)

  stockDetailModalApi.setData({rowData: {...deepCopiedRow,purchase_type_text:info.purchase_type_text,remark:info.remark},edit:inputDisabled}).open()
}

function closeStock(res:any){
  console.log('返回',res)
  const tableData = gridApi.grid.getData();
  const index = tableData.findIndex(item => item.goods_no === goods_no.value);
 if (index !== -1) {
   tableData[index].stock_data=res.data;
   tableData[index].stock_detail=res.data;
   tableData[index].confirm_num=res.total_num;
 }
  gridApi.setGridOptions({data:tableData})
  console.log(tableData)
  goods_no.value = ''
}

function del(row: any){
    const goods_no =row.goods_no
  const tableData = gridApi.grid.getData();
  const index = tableData.findIndex(item => item.goods_no === goods_no);
  if (index !== -1) {
    tableData.splice(index, 1)
  }
  gridApi.setGridOptions({data:tableData})
}


function editBut(){
  inputDisabled.value = false
}

function cancelBut(){
  modalApi.close()
}
//保存按钮
function savePurchase(){

  info.is_completed_warehouse = 0
  // if (!info.supply_id) {
  //   message.error('请先选择供应商')
  //   return
  // }
  const bom_list = gridApi.grid.getData();
  if (!bom_list.length ) {
    message.error("请先选择货品")
    return;
  }

  // 检查是否存在供应商不匹配的货品
  const hasMismatch = info.bom_list.some(row => !row.supply_ids.includes(info.supply_id));
  if (hasMismatch) {
    AntModal.confirm({
      title: '提示',
      content: '货品供应商与采购单供应商不一致',
      okText:'继续提交',
      cancelText:'返回修改',
      onOk() {
        handleSubmit()
      },
      onCancel() {},
    });
  } else {
    // 所有货品供应商匹配，直接提交
    handleSubmit();
  }
}

const handleSubmit = () => {
  info.bom_list = gridApi.grid.getData();
  //如果是编辑
  if(edit.value=='edit'){
     modalApi.lock()
    editGoodsPurchase(info).then((res:any) => {
      inputDisabled.value = true

      if (res.data.code === 1) {
        message.success(res.data.msg)
        goods_purchase_id.value = res.data.data.goods_purchase_id
        if(info.only_warehouse === 1) {
          info.is_completed_warehouse = 1
        } else {
          info.is_completed_warehouse = 0
        }
      }else{
        message.error(res.data.msg)
      }


      modalApi.unlock()
    })
  } else if (edit.value=='add'){
    createGoodsPurchase(info).then((res) => {
      if (res.data.code === 1) {
        message.success(res.data.msg)
        edit.value = 'edit'
        info.posted = 0
        info.goods_purchase_sn = res.data.data.goods_purchase_sn
        info.goods_purchase_id = res.data.data.goods_purchase_id
        goods_purchase_id.value = res.data.data.goods_purchase_id
        inputDisabled.value = true
      }else{
        message.error(res.data.msg)

      }

      modalApi.unlock()
    })
  }


  console.log(info)
}
// 分仓完成
const completeWarehouse = () => {
  info.only_warehouse = 1;
   handleSubmit()
}

//审核
const handleApproval = (purchase_id:any) => {
  const ids = [purchase_id]
  approval({ids: ids}).then((res:any) => {
    console.log(res)
    if (res.data.code !== 1) {
      message.error(res.data.msg)
      return
    }
    info.posted = 1;
    message.success('审核成功')
  })
}

// 反审
const [againstDialogModal, againstDialogModalApi] = useVbenModal({
  connectedComponent:againstDialog,
  destroyOnClose: true,
})


function handleAgainstNew(){
  let sel_arr = [{
    goods_purchase_id: info.goods_purchase_id,
    goods_purchase_sn: info.goods_purchase_sn,
  }];
  againstDialogModalApi.setData({data:sel_arr}).open()
}

function closeAgain(){
  initData(info.goods_purchase_id)
}

//标记完成
function handleCompleted(){
    const  list = gridApi.grid.getRadioRecord()

    if(!list.goods_id){
      message.error('请选择')
    }else {
      AntModal.confirm({
        title: '提示',
        content: '标记完结后不可取消,请确认!',
        okText:'是',
        cancelText:'否',
        onOk() {
          modalApi.lock(true)
          const params = {
            list:[list.product_id] ,
            goods_purchase_id:list.goods_purchase_id
          }
          markDetailComplete(params).then( res => {
            message.success(res.data.msg)
            modalApi.unlock()
          })
        },
        onCancel() {},
      });
    }
}



//弹框生命周期
const [Modal, modalApi] = useVbenModal({
  destroyOnClose: true,
  fullscreen: true,
  appendToMain: true,
  showCancelButton: false,
  showConfirmButton: false,
  onCancel() {
    modalApi.close()
  },
  async onConfirm() {

  },
  onOpenChange: async (isOpen: boolean) => {
    handleWareHouseSearch()
    handleFactorySearch()
    handleFactoryAllSearch()
    getRemoteBaseOption()
    DictAddInit({keys: ["paymentMethod","paymentRule"], type:2,}).then((result:any)=>{
      dictArr.value = result.select_list;
      dictArr.value.paymentMethod = result.select_list.paymentMethod.map((item:any)=>({
        label: item.name,
        value: item.value,
        code: item.name,
        id: Number(item.id),
      }))
      // 初始化结算规则并添加禁用状态
      dictArr.value.paymentRule = result.select_list.paymentRule.map((item:any)=>({
        label: item.name,
        value: item.name,
        code: item.value,
        disabled: false
      }))
    })
    if (!isOpen) return

    const { rowData ,view } = modalApi.getData<Record<string, any>>()
    edit.value = view
    if (view=='edit') {
      inputDisabled.value = true
      if(rowData){
        modalApi.lock()
        getGoodsPurchase({goods_purchase_id: rowData.goods_purchase_id}).then((result:any)=>{
          modalApi.unlock()
          Object.assign(info, result.row)
          gridApi.setGridOptions({data:info.bom_list})
          console.log(result.row)
        })
      }
    }else {
      inputDisabled.value = false
      info.goods_purchase_sn=''
      info.purchase_date =''
      info.warehouse_id =''
      info.supply_id =''
      info.purchase_type =''
      info.manual_no =''
      info.fk_type =''
      info.fk_rule =''
      info.remark =''
      info.pack_factory =[]
      info.purchase_type_text =''
      info.is_completed_warehouse =0
      info.bom_list =[]
      gridApi.setGridOptions({data:[]})
    }
    //是编辑

  },
})

function initData(goods_purchase_id:any) {
    getGoodsPurchase({goods_purchase_id:goods_purchase_id}).then((result:any)=>{
      Object.assign(info, result.row)
      gridApi.setGridOptions({data:info.bom_list})
    })




}
</script>

<template>
  <Modal  title="采购单详情">
    <Descriptions :column="5" bordered size="small" :label-style="{ width: '100px' }" :content-style="{ width: '180px' }">
        <Descriptions.Item label="采购时间">
          <DatePicker :disabled="inputDisabled" v-model:value="info.purchase_date" format="YYYY/MM/DD"  class="fixed-width-select"  placeholder="选择日期" value-format="YYYY-MM-DD"/>

        </Descriptions.Item>
        <Descriptions.Item label="采购单号">
          <Tag  class="fixed-width-select">{{ info.goods_purchase_sn || '自动生成'}}</Tag>
        </Descriptions.Item>
        <Descriptions.Item label="收货仓库">
          <Select
            class="fixed-width-select"
            v-model:value="info.warehouse_id"
            :disabled="inputDisabled"
            show-search
            allow-clear
            placeholder="请选择收货仓库"
            :filter-option="false"
            :options="wareHouseOptions"
            :loading="factoryhandleLoading"
            @search="handleWareHouseSearch"
            @dropdown-visible-change="handleWarehouse"
          />
        </Descriptions.Item>
        <Descriptions.Item label="订单性质">
          <Select
            v-model:value="info.purchase_type"
            :options="typeOptinos"
            placeholder="请选择订单属性"
            show-search
            allow-clear
            :disabled="inputDisabled"
            class="fixed-width-select"
            @change="purchasetypeChange"
          />
        </Descriptions.Item>
        <Descriptions.Item label="供应商">
          <Select
            class="fixed-width-select"
            v-model:value="info.supply_id"
            show-search
            allow-clear
            placeholder="请选择供应商"
            :disabled="inputDisabled"
            :filter-option="false"
            :options="factoryOptions"
            :loading="factoryhandleLoading"
            @search="handleFactorySearch"
            @dropdown-visible-change="handleFactory"
          />
        </Descriptions.Item>
        <Descriptions.Item label="手工单号">
          <Input class="fixed-width-select" :disabled="inputDisabled"  v-model:value="info.manual_no"  placeholder="手工单号"/>
        </Descriptions.Item>
        <Descriptions.Item label="结算方式">
          <Select   class="fixed-width-select" :disabled="inputDisabled" :options="dictArr.paymentMethod" v-model:value="info.fk_type" :placeholder="'结算方式'" @change="refreshfkRule"/>
        </Descriptions.Item>
        <Descriptions.Item label="结算规则">
          <Select  class="fixed-width-select" :disabled="inputDisabled" :options="dictArr.paymentRule" v-model:value="info.fk_rule" :placeholder="'结算方式'" @change="fktypeChange"/>
        </Descriptions.Item>
        <Descriptions.Item :span="2" label="备注">
          <Input class="w-full" :disabled="inputDisabled" v-model:value="info.remark" placeholder="备注"/>
        </Descriptions.Item>
        <Descriptions.Item :span="5" label="包装厂">
          <Select
            class="w-full"
            v-model:value="info.pack_factory"
            show-search
            allow-clear
            :disabled="inputDisabled"
            placeholder="请选择包装厂"
            :filter-option="false"
            :options="factoryAllOptions"
            :loading="factoryAllhandleLoading"
            @search="handleFactoryAllSearch"
            @dropdown-visible-change="handleFactoryAll"
            mode="multiple"
          />
        </Descriptions.Item>
      </Descriptions>
    <Grid>
      <template #operation="{ row }">
        <Button  danger size="small" @click="del(row)">删除</Button>
      </template>
      <template #style_category_id="{ row }">
        <Cascader v-model:value="row.style_category_id" style="width: 100%"  :options="baseOption.styleCategory" />
      </template>
      <template #stock_data="{ row }">
        <span style="color: #3b82f6" class="c-blue" @click="showStockDetail(row)">调整分仓</span>
      </template>

      <template #is_completed="{ row }">
        {{row.is_completed == 1 ? '已完成' : '未完成'}}
      </template>
      <template #dead_line="{ row }">
        <DatePicker  :disabled="inputDisabled" v-model:value="row.dead_line" format="YYYY/MM/DD"  class="w-full"  placeholder="选择日期" value-format="YYYY-MM-DD"/>
      </template>
      <template #remark="{ row }">
        <Input class="w-full"   :disabled="inputDisabled" v-model:value="row.remark"  placeholder="请输入备注"/>
      </template>
      <template #other_pay_remark="{ row }">
        <Input class="w-full"  :disabled="inputDisabled"  v-model:value="row.other_pay_remark"  placeholder="其他付款方式备注"/>
      </template>
      <template #component="{ row }">
        <Row style="width: 100%">
          <Col span="16">
            <Input  v-model:value="row.component"  :disabled="inputDisabled"  placeholder="请输入成分"/>
          </Col>
          <Col span="8">
            <Button size="small"  @click="openUpdateLog(row)">变更记录</Button>
          </Col>
        </Row>
      </template>

    </Grid>

    <template #prepend-footer>
      <Button  @click="cancelBut">取消</Button>
      <Button type="primary" v-if="!inputDisabled" @click="openGoods()">批量新增</Button>

      <Button type="primary"  v-if=" info.goods_purchase_id > 0 && info.posted == 0 && inputDisabled" @click="handleApproval(info.goods_purchase_id)" danger>审核</Button>
      <Button type="primary" class="bg-green-500" v-if=" info.goods_purchase_id > 0 && info.is_completed != 1 && info.posted > 0" @click="handleCompleted()" >标记完成</Button>

      <Button type="primary"  v-if="info.goods_purchase_id > 0 && info.posted > 0 && inputDisabled" @click="handleAgainstNew()" danger>反审</Button>

      <Button type="primary"  v-if="inputDisabled && info.posted == 0"  class="bg-orange-400" @click="editBut()">修改</Button>
      <template v-if="!inputDisabled">
        <Button type="primary"   @click="savePurchase()">保存</Button>
      </template>
      <Button type="primary" v-if="info.goods_purchase_id > 0" @click="completeWarehouse">分仓完成</Button>
    </template>
    <goodsModal @push-data="handlePushGoods"/>
    <updateLogModal/>
    <stockDetailModal @close="closeStock"/>
    <againstDialogModal  @close="closeAgain"/>
  </Modal>
</template>

<style lang="scss" scoped>
.fixed-width-select {
  width: 160px;
}
</style>
